package edu.xpu.cs.hub.controller;

import edu.xpu.cs.hub.entity.User;
import edu.xpu.cs.hub.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class ShiroController {

    @Autowired
    UserServiceImpl userServiceImpl;

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,hub");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装登陆用户的登陆数据
        UsernamePasswordToken passwordToken = new UsernamePasswordToken(username,password);

        try {
            subject.login(passwordToken);//执行登陆的方法，如果没有异常就说明好了
            return "file";
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e) {//密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//拿到user对象
        // 如果已经登录，则跳转到管理首页
        if(currentUser != null){
            SecurityUtils.getSubject().logout();
        }
        return "redirect:" + "login";
    }

    @RequestMapping("/query")
    public User queryUserByName(String name){
        return userServiceImpl.queryUserByName(name);
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unAuthorized(){
        return "未经授权，不能访问此页面";
    }
}
